import os
import re
import logging
import subprocess

import settings
import connector.connector

log = logging.getLogger(settings.log_name_applog)


def __url_convert(raw):
    #old method which downloads files in bulk (cannot handle exceptions)

    #pattern = '\n'
    #replaceby = ' '
    #
    #result = re.compile(pattern).sub(replaceby, raw)

    result = raw.split()

    return result


def __get_url():
    filepath = open(connector.connector.get_latest_link_log_filepath(), 'r')

    result = filepath.read()
    filepath.close()

    return result


def __download_validation(text):
    pattern = settings.download_log_finish_pattern
    return not re.search(pattern, text) is None


def __call_tp_application(urls):
    if os.path.getsize(connector.connector.get_latest_link_log_filepath()) <= 0:
        raise Exception(settings.empty_file_exception)

    filepath = connector.connector.init_latest_downloader_log_filepath()
    filestream = open(filepath, 'a')
    downloader_path = settings.third_party_downloader_path
    log.info('got url(s): ' + '.'.join(urls))
    options = settings.third_party_downloader_option
    command = downloader_path + ' ' + options

    log.debug('download command: ', command)

    log.info('start downloading video(s).')

    for url in urls:
        pp = subprocess.Popen(command + ' ' + url, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        try:
            result = connector.connector.print_stdout_output(pp)

        except KeyboardInterrupt:
            print 'video download process stopped by user.'
            log.warning('video download process stopped by user.')
            return

        except Exception, e:
            print 'unexpected error:'
            print e
            log.info(settings.downloader_logging_file_failed_pattern + url)

        else:
            if __download_validation(result):
                log.info(settings.downloader_logging_file_completed_pattern  + url)

            else:
                log.info(settings.downloader_logging_file_failed_pattern + url)

        filestream.write(result)

        pp.kill()

    filestream.close()

    log.info('video download process stopped.')


def download(urls):
    if urls == 'N/A':
        urls = __url_convert(__get_url())

    __call_tp_application(urls)


def download_previous():
    filepath = connector.connector.get_latest_downloader_todo_log_filepath()

    if filepath and filepath is not 'EMPTY':
        filestream = open(filepath, 'r')
        result = filestream.read()
        filestream.close()

        if result is not None:
            download(__url_convert(result))

    else:
        pass


if __name__ == '__main__':
    try:
        download_previous()
        download('N/A')

    except Exception, e:
        if e.message == settings.empty_file_exception:
                print "file is empty."